﻿using Common;
using Common.Communications;
using Common.Model;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpticalService
{
    /// <summary>
    /// 光通信服务总入口
    /// </summary>
    public class TransferOpticalService
    {

        #region 属性
        private List<OpticalServiceModel> opticalServiceInfos = new List<OpticalServiceModel>();
        private ConcurrentBag<TcpCommunication> tcpComList = new ConcurrentBag<TcpCommunication>();
        #endregion

        #region 构造
        public TransferOpticalService(Func<TcpReciveModel,Task> reciveProcess) 
        {
            InitOpticalService();
            CreatOpticalCom(reciveProcess);
        }
        #endregion

        #region private
        private void InitOpticalService()
        {
            var rcsSetting = AppSetting.Instance.settingMultipleModels.FirstOrDefault(s => s.SettingType == ConstString.OpticalServiceKey);
            if (rcsSetting is null)
            {
                Log.Error($"光通信参数配置不存在");
                return;
            }
            try
            {
                if (rcsSetting.ModelType != typeof(List<OpticalServiceModel>))
                {
                    Log.Error($"光通信参数配置错误");
                    return;
                }
                var infos = JsonConvert.DeserializeObject(rcsSetting.Values, rcsSetting.ModelType);
                opticalServiceInfos = infos as List<OpticalServiceModel>;
            }
            catch (Exception ex)
            {
                Log.Error($"光通信参数读取异常");
            }
        }
        /// <summary>
        /// 创建光通信模块间的通信
        /// </summary>
        private void CreatOpticalCom(Func<TcpReciveModel, Task> action)
        {
            if (opticalServiceInfos.Any())
            {
                foreach (var item in opticalServiceInfos)
                {
                    TcpCommunication tcpCom= new TcpCommunication();
                    var flag = tcpCom.Connect(item.Ip,int.Parse(item.Port));
                    if (flag)
                    {
                        tcpCom.ReciveChange += action;
                        tcpComList.Add(tcpCom);
                    }
                }
            }
        }
        #endregion
        /// <summary>
        /// 发送
        /// </summary>
        /// <returns></returns>
        public async Task<bool> SendMsgProcsssAsync(string para)
        {
            var flag = false;
            if (tcpComList is null)
            {
                return false;
            }
            foreach (var com in tcpComList)
            {
                var result = await com.SendAsync(para);
                flag = flag ? flag : result;
            }
            if (flag)
            { 
                return true;
            }
            return false;
        }
    }
}
